package com.common.config;



import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpConfig {

    public static void initOkHttp() {
        // 创建一个拦截器来添加请求头
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder requestBuilder = originalRequest.newBuilder();

                // 添加公共请求头
                requestBuilder.header("Content-Type", "application/json");
                requestBuilder.header("client", "app");

                // 如果 token 不为空，添加到请求头
                if (Constants.Authorization != null && !Constants.Authorization.isEmpty()) {
                    requestBuilder.header("Authorization", Constants.Authorization);
                }

                Request request = requestBuilder.method(originalRequest.method(), originalRequest.body()).build();
                return chain.proceed(request);
            }
        };

        // 创建 OkHttpClient 实例并设置超时时间和拦截器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(headerInterceptor)
                .build();

        // 配置 OkHttpUtils
        OkHttpUtils.initClient(okHttpClient);
    }
}
